package edu.wit.service;

import edu.wit.common.api.RemoteLogService;
import edu.wit.common.api.RemoteUserinfoService;
import edu.wit.common.api.domain.SysLogininfor;
import edu.wit.common.api.domain.SysUser;
import edu.wit.common.api.model.LoginUser;
import edu.wit.common.constant.Constants;
import edu.wit.common.constant.UserConstants;
import edu.wit.common.core.domain.R;
import edu.wit.common.enums.UserStatus;
import edu.wit.common.exception.BaseException;
import edu.wit.common.utils.SecurityUtils;
import edu.wit.common.utils.ServletUtils;
import edu.wit.common.utils.StringUtils;
import edu.wit.common.utils.ip.AddressUtils;
import edu.wit.common.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

/**
 * 登录校验方法
 * 
 * @author lee
 */
@Component
public class SysLoginService {
    @Autowired
    private RemoteLogService remoteLogService;

    @Autowired
    private RemoteUserinfoService remoteUserService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new BaseException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new BaseException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new BaseException("用户名不在指定范围");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username);

        if (R.FAIL == userResult.getCode()) {
            throw new BaseException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData().getSysUser())) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new BaseException("登录用户：" + username + " 不存在/用户名错误");
        }
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();

        if (UserStatus.DELETED.getCode().equals(user.getIsDeleted() + "")) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }

        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            this.saveLogininfor(username, Constants.LOGIN_FAIL, "用户密码错误");
            throw new BaseException("用户密码错误");
        }
        this.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");

        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("user-agent"));
        userInfo.setBrowser(userAgent.getBrowser().getName());
        userInfo.setOs(userAgent.getOperatingSystem().getName());
        userInfo.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        remoteUserService.updateLoginIp(userInfo);
        return userInfo;
    }

    public void logout(String loginName) {
        this.saveLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    public void saveLogininfor(String username, String status,String message) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("user-agent"));

        // 封装对象
        SysLogininfor logininfor = new SysLogininfor();
        logininfor.setUserName(username);
        logininfor.setIpaddr(ip);
        logininfor.setMsg(message);

        logininfor.setAddress(AddressUtils.getRealAddressByIP(ip));
        logininfor.setBrowser(userAgent.getBrowser().getName());
        logininfor.setOs(userAgent.getOperatingSystem().getName());

        logininfor.setAccessTime(new Date());

        // 日志状态
        if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
            logininfor.setStatus("0");
        } else if (Constants.LOGIN_FAIL.equals(status)) {
            logininfor.setStatus("1");
        }
        //远程调用保存登录日志
        remoteLogService.saveLogin(logininfor);
    }
}